package com.atguigu.juc.homework;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class   Ticket{
    private int ticket = 50;
   /* public synchronized void getTicket(){
        if (ticket>0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("这个线程名为"+Thread.currentThread().getName()+"刚刚卖出了第"+(ticket--)+"张票"+"------>现在还剩余"+ticket+"张票");
        }
    }*/
   Lock lock=new ReentrantLock();
    public  void getTicket(){

            lock.lock();
        if (ticket>0){
            try {
                Thread.sleep(100);
                System.out.println("这个线程名为"+Thread.currentThread().getName()+"刚刚卖出了第"+(ticket--)+"张票"+"------>现在还剩余"+ticket+"张票");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

        }
    }
}


public class JucTest {
    public static void main(String[] args) {
        //练习要求是三个线程买50张票
        //多线程应该考虑是        线程       资源类       操作
        Ticket ticket = new Ticket();
        /*new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i <50 ; i++) {
                    ticket.getTicket();
                }

            }
        },"卖票窗口1").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <51 ; i++) {
                    ticket.getTicket();
                }

            }
        },"卖票窗口2").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <51 ; i++) {
                    ticket.getTicket();
                }
            }
        },"卖票窗口3").start();*/

        //lamda表达式的线程写法  runable接口是函数式接口
        new Thread(() -> { for (int i = 0; i <50 ; i++) { ticket.getTicket();} },"1号窗口").start();

        new Thread(() -> { for (int i = 0; i <50 ; i++) { ticket.getTicket();} },"2号窗口").start();

        new Thread(() -> { for (int i = 0; i <50 ; i++) { ticket.getTicket();} },"3号窗口").start();
    }
}
